package com.btkjgc.service.impl;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.btkjgc.models.AdminUser;
import com.btkjgc.models.AjaxObj;
import com.btkjgc.models.Dictionary;
import com.btkjgc.models.RechargeRecord;
import com.btkjgc.models.extend.RechargeRecordModel;
import com.btkjgc.service.intf.RechargeManageService_Intf;
import com.btkjgc.utils.DateUtils;
import com.btkjgc.utils.ExcelExportor;
import com.btkjgc.utils.HibernateUtil;
import com.btkjgc.utils.HttpUtils;
import com.btkjgc.utils.LogUtils;

@Service
public class RechargeManageService_Impl extends BaseService_Impl implements RechargeManageService_Intf
{

	@Override
	public void setListData(HttpServletRequest request, ModelAndView mv, int pageIndex, int totalRecord,
			List<RechargeRecordModel> privateRechargeRecord) {
		// TODO Auto-generated method stub
		
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements())
		{
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
		
		mv.addObject("recharge_record_p", privateRechargeRecord);
		
		//站点列
		String sitesql = " select DISTINCT ecst.name as value,CONCAT(ecst.id,'') 'key' from electric_charging_site_t ecst" +
						 " LEFT JOIN recharge_record_t rrt ON rrt.siteid=ecst.id where rrt.del = 0";
		
		List<Dictionary> siteList = HibernateUtil.executeSQLQueryList(sitesql,Dictionary.class);
		if(siteList.size() > 0)
		{
			mv.addObject("siteList", siteList);
		}
		
		//充值方式列
		String typesql = " SELECT dt.`key`,dt.`value` FROM dictionary_t dt WHERE dt.`name`='RechargeType'";
		
		List<Dictionary> typeList = HibernateUtil.executeSQLQueryList(typesql, Dictionary.class);
		if(typeList.size() > 0)
		{
			mv.addObject("typeList", typeList);
		}
		
		//搜索手机号码列
		String telsql = "SELECT aut.tel as name,CONCAT(id, '') 'key' FROM account_user_t aut WHERE aut.del = 0 AND aut.type=0";
		
		List<Dictionary> telList = HibernateUtil.executeSQLQueryList(telsql, Dictionary.class);
		if(telList.size() > 0)
		{
			mv.addObject("telList", telList);
		}
		
		mv.addObject("currentpage", pageIndex);
		mv.addObject("totalRecord", totalRecord);
		
	}

	@Override
	public void setListData1(HttpServletRequest request, ModelAndView mv, int pageIndex1, int totalRecord1,
			List<RechargeRecordModel> companyRechargeRecord) {
		// TODO Auto-generated method stub
		
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements())
		{
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
		
		mv.addObject("recharge_record_c", companyRechargeRecord);
		
		//公司列
		String companysql = " select aut.name,CONCAT(id,'') 'key' from account_user_t aut where aut.type=1 and aut.del = 0";
		
		List<Dictionary> companyList = HibernateUtil.executeSQLQueryList(companysql,Dictionary.class);
		if (companyList.size() > 0)
		{
			mv.addObject("companyList", companyList);
		}
		
		mv.addObject("currentpage1", pageIndex1);
		mv.addObject("totalRecord1", totalRecord1);
		
	}

	@Override
	public AjaxObj updatePrivateRecharge(RechargeRecordModel rechargeRecordModel) {
		// TODO Auto-generated method stub
		String d=new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
		String rcgdate=new SimpleDateFormat("HH:mm").format(Calendar.getInstance().getTime());
		
		AjaxObj ajaxObj=new AjaxObj();
		ajaxObj.setResult(true);
		RechargeRecord rechargeRecord = new RechargeRecord();
		AdminUser adminUser = getLoginUser();
		
		//设置serialNum
		int length = rechargeRecordModel.getAccountid().toString().length();
		String serialNum = "";
		serialNum = serialNum+d;
		for(int i=0;i<10-length;i++){
			serialNum+="0";
		}
		serialNum=serialNum+rechargeRecordModel.getAccountid();
		
		Integer ab = (int)rechargeRecordModel.getBalance()*100+rechargeRecordModel.getAmount();
		
		try{
			rechargeRecord.setAccountid(rechargeRecordModel.getAccountid());
			rechargeRecord.setType(0);
			rechargeRecord.setAmount(rechargeRecordModel.getAmount());
			rechargeRecord.setCreatedate(new Date());
			rechargeRecord.setDel(0);
			//设置充值类型
			rechargeRecord.setRechargeType(2);
			rechargeRecord.setRechargeWay(3);
			rechargeRecord.setOperid(adminUser.getId());
			//设置充值站点
			//rechargeRecord.setSiteid(siteid);
			rechargeRecord.setSerialNum(serialNum);
			rechargeRecord.setReason(rechargeRecordModel.getReason());
			HibernateUtil.save(rechargeRecord);
			
			//更新AccountInfo余额
			String hql = " update from AccountInfo" +
						 " set" +
						 " available_balance=" +ab+
						 " where accountid=" +rechargeRecordModel.getAccountid();
			
			HibernateUtil.executeUpdate(hql);
			
			//推送消息
			String sql = " select tel from account_user_t where id=" +rechargeRecordModel.getAccountid();
			String tel = (String)HibernateUtil.executeSQLQueryObject(sql);
			Map<String, String> mapParam = new HashMap<String, String>();
			String str="【充值提醒】尊敬的车主：您于"+rcgdate+"通过财务充值"+rechargeRecordModel.getAmount()/100+"元，充值账户余额"+ab/100+"元。";
			str=new String(str.getBytes("utf-8"),"8859_1");
			mapParam.put("service", "account_change_notify_to_alipay");
			mapParam.put("msg", str);
			mapParam.put("phone", tel);
			String pathUrl = "http://fare.botann.com/btkjsite_fuwuhao/btgateway.do";
			HttpUtils.postUrlAsString(pathUrl, mapParam);
		}catch (Exception e) {
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("充值时出错");
		}
		return ajaxObj;
	}

	@Override
	public AjaxObj updateCompanyRecharge(RechargeRecordModel rechargeRecordModel) {
		// TODO Auto-generated method stub
		String d=new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
		String rcgdate=new SimpleDateFormat("HH:mm").format(Calendar.getInstance().getTime());
		
		AjaxObj ajaxObj=new AjaxObj();
		ajaxObj.setResult(true);
		RechargeRecord rechargeRecord = new RechargeRecord();
		AdminUser adminUser = getLoginUser();
		
		//设置serialNum
		int length = rechargeRecordModel.getAccountid().toString().length();
		String serialNum = "";
		serialNum = serialNum+d;
		for(int i=0;i<10-length;i++){
			serialNum+="0";
		}
		serialNum=serialNum+rechargeRecordModel.getAccountid();
				
		Integer ab = (int)rechargeRecordModel.getBalance()*100+rechargeRecordModel.getAmount();
		
		try{
			rechargeRecord.setAccountid(rechargeRecordModel.getAccountid());
			rechargeRecord.setType(1);
			rechargeRecord.setAmount(rechargeRecordModel.getAmount());
			rechargeRecord.setCreatedate(new Date());
			rechargeRecord.setDel(0);
			rechargeRecord.setRechargePerson(rechargeRecordModel.getRechargePerson());
			rechargeRecord.setTel(rechargeRecordModel.getTel());
			//设置充值类型
			rechargeRecord.setRechargeType(2);
			rechargeRecord.setRechargeWay(3);
			rechargeRecord.setOperid(adminUser.getId());
			//设置充值站点
			//rechargeRecord.setSiteid(siteid);
			rechargeRecord.setSerialNum(serialNum);
			rechargeRecord.setReason(rechargeRecordModel.getReason());
			HibernateUtil.save(rechargeRecord);
			
			//更新AccountInfo余额
			String hql = " update from AccountInfo" +
						 " set" +
						 " available_balance=" +ab+
						 " where accountid=" +rechargeRecordModel.getAccountid();
			
			HibernateUtil.executeUpdate(hql);
			//推送消息
			String sql = " select tel from account_user_t where id=" +rechargeRecordModel.getAccountid();
			String tel = (String)HibernateUtil.executeSQLQueryObject(sql);
			Map<String, String> mapParam = new HashMap<String, String>();
			Map<String, String> header = new HashMap<String, String>();
			mapParam.put("service", "account_change_notify_to_alipay");
			mapParam.put("msg", "【充值提醒】贵公司于"+rcgdate+"通过财务充值"+rechargeRecordModel.getAmount()/100+"元，充值账户余额"+ab/100+"元。");
			mapParam.put("phone", tel);
			header.put("encode", "utf-8");
			String pathUrl = "http://114.55.7.104/btkjsite_fuwuhao/btgateway.do";
			HttpUtils.postUrlAsString(pathUrl, mapParam, header);
		}catch (Exception e) {
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("充值时出错");
		}
		return ajaxObj;
	}

	@Override
	public void doDownloadAction(HttpServletRequest request,
			HttpServletResponse response, String sql) {
		// TODO Auto-generated method stub
		ExcelExportor<String[]> exproter = new ExcelExportor<String[]>();
		try
		{
			String entity = null;
			String export =request.getParameter("export");
			if ("1".equals(export)) {
				entity="公司";
			} else if ("0".equals(export)) {
				entity="个人";
			}
			
			response.setHeader("content-disposition", "attachment;filename="
					+ URLEncoder.encode(DateUtils.getDateTime("yyyyMMdd")+entity+"充值记录列表.xls", "UTF-8"));
			OutputStream out = response.getOutputStream();
			
			List<RechargeRecordModel> items = HibernateUtil.executeSQLQueryList(sql,RechargeRecordModel.class);
			
			List<String[]> rows = new ArrayList<String[]>();
			
			String[] header =  new String[] { "日期", "账号", "所属"+entity,
					"手机号", "充值金额", "充值站点", "充值方式", "充值人", "联系电话", "操作员"};
			
			for(RechargeRecordModel item : items)
			{
				String[] row = new String[header.length];
				row[0] = DateUtils.formatDate(item.getCreatedate(), "yyyy-MM-dd HH:mm:ss");
				row[1] = item.getAccount();
				
				row[2] = item.getUsername();
				row[3] = item.getPhone();
				row[4] = String.valueOf(item.getAmount()/100);
				
				row[5] = item.getName();
				row[6] = item.getValue();
				row[7] = item.getRechargePerson();
				
				row[8] = item.getTel();
				row[9] = item.getOpername();
				rows.add(row);
			}
			exproter.exportExcel(DateUtils.getDateTime("yyyyMMdd")+entity+"充值记录列表", header, rows, out, null);
		}
		catch (Exception e)
		{
			LogUtils.error(e);
		}
	}

	@Override
	public void deleteById(Integer rechargeRecordId) {
		// TODO Auto-generated method stub
		AdminUser loginUser = getLoginUser();
		
		List hqlList=new ArrayList<>();
		String hql = " update from RechargeRecord set del=1,"+
					 " operid=" +loginUser.getId()+
					 " where id=?";
		hqlList.add(hql);
		
		List paramLists=new ArrayList<>();
		List paramLists2 =new ArrayList<>();
		paramLists2.add(String.valueOf(rechargeRecordId));
		paramLists.add(paramLists2);
		paramLists.add(paramLists2);
		HibernateUtil.batchExecuteUpdate(hqlList, paramLists);
		
	}
	
}